import express from "express";
import bodyParser from "body-parser";
import { uploadFileToIPFS, uploadJSONToIPFS } from "./lib/UploadToIpfs.js";
import { mint } from "./lib/NFTMinter.js";
import {
  writePetsInfo,
  readPetsInfo,
  getPetInfo,
  deletePetsInfo,
} from "./lib/UpdatePetsJSON.js";
import { mintUSDT } from "./lib/USDTMinter.js";
import fileUpload from "express-fileupload";
// import path from "path";
import cors from "cors";
import dotenv from "dotenv";
import fs from "fs";
import { error } from "console";
// import { multiaddr } from "kubo-rpc-client";
dotenv.config("./.env");
const app = express();
const port = process.env.PORT;
const host = process.env.HOST;

// enable cross-origin
app.use(
  cors({
    origin: ["http://localhost:3000", "http://127.0.0.1:7897"],
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE", // 允许的 HTTP 方法
    credentials: true, // 允许发送身份验证凭证
  })
);
app.use(fileUpload());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
// const storage = multer.memoryStorage();
// const upload = multer({ storage: storage });

const uploadsFolder = "./files/";
// app.use("./uploads", express.static("uploads"));

app.get("/get", (req, res) => {
  res.json({ name: "get" });
  console.log("get");
});
app.post("/mint", async (req, res) => {
  try {
    const address = req.body.address;
    const amount = req.body.amount;
    const result = mintUSDT(amount, address);
    res.json(result);
    console.log(result);
  } catch (err) {
    console.log(err);
    res.status(500).json({ error: "MINTUSD ERROR" });
  }
});
app.post("/upload", async (req, res) => {
  // console.log(req);
  try {
    const title = req.body.title;
    const description = req.body.message;
    const price = req.body.price;
    // image file will be upload to ipfs
    const file = req.files.file;
    const seller = req.body.address;
    console.log(seller);
    const fileName = file.name;
    const filePath = "./files/" + fileName;
    console.log("recive post");
    // const filePath = path.join(uploadsFolder, fileName);
    await file.mv(filePath, async (err) => {
      console.log(err);
      // res.status(500).send(err);
    });
    const result = await uploadFileToIPFS(filePath, file.data);
    console.log(result);

    const images =
      "https://ipfs.io/ipfs/" + result.cid.toString() + "/" + fileName;
    const mateData = {
      title: title,
      description: description,
      image: images,
    };
    const matedataResult = await uploadJSONToIPFS(mateData);
    console.log("upload ipfs success");
    console.log("mint NFT...");
    const tokenId = await mint(seller, matedataResult.path);

    console.log("mint success");
    // update the pet info
    const newPetsInfo = {
      tokenId: tokenId.toString(),
      title: title,
      description: description,
      price: price,
      images: images,
      seller: seller,
      matedata: matedataResult.cid,
    };
    await writePetsInfo(newPetsInfo);
    res.json({
      message: "upload success",
      tokenId: tokenId.toString(),
      metadata: mateData,
    });
    // console.log(`title:${title}`, `description:${description}`, `file:${file}`);
  } catch (error) {
    console.error("Error uploading file:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
app.get("/petlist", async (req, res) => {
  const pets = await readPetsInfo();
  res.json(pets);
});
app.post("/charge", async (req, res) => {
  console.log("req" + req.body.address);
  const address = req.body.address;
  const amount = req.body.amount;
  try {
    mintUSDT(address, amount);
  } catch (e) {
    res.status(500).json({ error: e });
  }
});
app.get("/getPetInfo", async (req, res) => {
  try {
    const tokenId = req.query.tokenId;
    const petInfo = await getPetInfo(tokenId);
    console.log(petInfo);
    res.json(petInfo);
  } catch (e) {
    console.log(e);
    res.status(500).json({ error: e });
  }
});
app.post("/buy", async () => {
  try {
    const tokenId = req.body.tokenId;
    console.log(tokenId);
    deletePetsInfo(tokenId);
  } catch (e) {
    console.log(e);
    res.status(500).json({ error: e });
  }
});
app.listen(port, host, () => {
  console.log(`Server is running on http://${host}:${port}`);
});
